import {developUrl,zuulHost,uamServer,developDK,tongxunDK} from '@/views/api/api'
const TOKEN = localStorage.token;
import Vue from 'vue';
import axios from 'axios';
let noteType =[];/*键名为10种环节类型，键值为7种页面类型*/
noteType[1]='6';
noteType[2]='6';
noteType[3]='6';
noteType[4]='5';
noteType[5]='2';
noteType[6]='6';
noteType[7]='6';  /*原来的旧版本可能要注释*/
//noteType[7]='7';/*罗显胜要求的第7种类型*/
noteType[8]='6';
noteType[9]='1';
noteType[10]='3';

noteType[11]='6';/*通用流程*/
noteType[12]='6';/*通用流程*/
noteType[13]='6';/*通用流程*/
noteType[14]='5';/*通用流程*/
noteType[15]='2';/*通用流程*/
noteType[16]='6';/*通用流程*/
noteType[17]='6';/*通用流程*/
noteType[18]='6';/*通用流程*/
noteType[19]='1';/*通用流程*/
noteType[20]='3';/*通用流程*/

noteType[100]='6';/*通用流程*/
let arr = [];


let waitType =[];/*待办类型*/
waitType['daichuli'] = "待处理";
waitType['daifenfa'] = "待分发";
waitType['daiqianshou'] = "待签收";
waitType['daishenpi'] = "待审批";
waitType['daifankui'] = "待反馈";
waitType['daibanjie'] = "待办结";
waitType['daipingjia'] = "待评价";
waitType['yiwanjie'] = "已完结";
waitType['yipingjia'] = "已评价";

export const getParam = (paramName)=>{/*获取参数*/
		paramValue =""; 
						  isFound =false; 
						  if (this.location.search.indexOf("?") ==0&&this.location.search.indexOf("=")>1){ 
						    arrSource = unescape(this.location.search).substring(1,this.location.search.length).split("&"); 
						    i =0; 
						    while (i < arrSource.length &&!isFound){ 
						      if (arrSource[i].indexOf("=") >0){ 
						        if (arrSource[i].split("=")[0].toLowerCase()==paramName.toLowerCase()){ 
						          paramValue = arrSource[i].split("=")[1]; 
						          isFound =true; 
						        } 
						      } 
						    i++; 
						    } 
						  } 
	    return paramValue;
}


export const apiWaitDanList = (ev,param) => {/*代办列表*/
	console.log(TOKEN);
  return axios({
    method : 'post',
   	headers : {
	    'Content-Type' : 'application/json'
	},
	url : developUrl+developDK+'act/selectByCondition?access_token='+TOKEN,
	data:{
		"startTime":param.applyTime[0],
		"endTime":param.applyTime[1],
		"userName":param.applyPerson,
		"applyTitle":param.applyThing,
		"waitType" : param.waitType,
		"pageQuery":{
			"pageNum":ev.pageNum,
			"pageSize":ev.pageSize
		}
	}
  }).then((res) => {
  	 console.log(res);
	if(res.data.code=='200'){
		ev.pageTotal = res.data.count;
		ev.tableData = res.data.codeData;
		for(let i in ev.tableData){
			ev.tableData[i].createTime = dealTime(ev.tableData[i].createTime);
			ev.tableData[i].delLastTime  =dealTime(ev.tableData[i].delLastTime );
			ev.tableData[i].applyDate = dealTime(ev.tableData[i].applyDate );
			
			ev.tableData[i].waitType  = waitType[ev.tableData[i].waitType];
		}
		console.log(ev.tableData)
	}else{
		ev.$message.error('网络出错，请稍后再试');
	}
  })
.catch((error) => {
	ev.$message.error('网络出错，请稍后再试');
   	console.log('出错',error);
 });
};


export const apiMyList = (ev,param) => {/*我的列表*/
  return axios({
    method : 'post',
   	headers : {
	    'Content-Type' : 'application/json'
	},
	url : developUrl+developDK+'synergetic/selectByCondition?access_token='+TOKEN,
	data:{
		"startTime":param.applyTime[0],
		"endTime":param.applyTime[1],
		"userName":param.applyPerson,
		"applyTitle":param.applyThing,
		"waitType" : param.waitType,
		"pageQuery":{
			"pageNum":ev.pageNum,
			"pageSize":ev.pageSize
		}
	}
  }).then((res) => {
  	 console.log(res);
  	if(res.data.code=='200'){
		ev.tableData = res.data.data;
		ev.pageTotal = res.data.count;
		for(let i in ev.tableData){
			ev.tableData[i].createDate = dealTime(ev.tableData[i].createDate);
			ev.tableData[i].arriveDate = dealTime(ev.tableData[i].arriveDate);
			ev.tableData[i].waitType  = waitType[ev.tableData[i].status];
			ev.tableData[i].orderType = ev.tableData[i].orderType==='myself'?'我申请的':'我处理的';
			ev.tableData[i].handlers  = String(ev.tableData[i].handlers).substring(0,10);
		}
  		console.log(ev.tableData)
  		

  	}else{
  		ev.$message.error('网络出错，请稍后再试');
  	}
  })
.catch((error) => {
	ev.$message.error('网络出错，请稍后再试');
   	console.log('出错',error);
 });
};


export const apiWaitDanDetail = (ev,params) => {/*获取工单详情*/
  return axios({
    method : 'post',
		url : developUrl+developDK+'synergetic/get/taskInfo?access_token='+TOKEN,
		headers : {
	     'Content-Type': 'application/x-www-form-urlencoded'
		},
		data:params,
		transformRequest: [function (data) {/*转成fromdata*/
              let ret = ''
              for (let it in data) {
                ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
              }
              return ret
        }],
  }).then((res) => {
  	 console.log(res);
	if(res.data.result.code=="200"||res.data.result.code==200){
		ev.baceInfo = res.data.result.data.form;
		ev.baceInfo.createDate = dealTime(ev.baceInfo.createDate);
		ev.detailType =noteType[res.data.result.data.nodeType];/*页面类型*/
		ev.noteType = res.data.result.data.nodeType;/*节点类型*/
		ev.processInstanceId =res.data.result.data.form.processInstanceId;
		if(res.data.result.data.hasOwnProperty('node')){
			ev.sid = res.data.result.data.node.sId;
		}
//		ev.detailType ='2';/*测试用写死*/
		ev.detail.btn=res.data.result.data.btn;
	}else{
		ev.$message.error('网络出错，请稍后再试');
	}
  })
.catch((error) => {
	ev.$message.error('网络出错，请稍后再试');
   console.log('出错',error);
 });
};


export const apiSubmitDetail =(ev,param)=>{/*工单详情提交*/
console.log(param);
return axios({
    method : 'post',
		url : developUrl+developDK+'synergetic/agent/complete?access_token='+TOKEN,
		headers : {
	    	'Content-Type': 'application/x-www-form-urlencoded'
		},
		data:{
				"flowId":param.inputFrom.myRadio,
				"opinion":param.inputFrom.myInput||"情况属实，同意提供",
				"taskId":param.taskId,
				"nodeType":ev.noteType,
				"handleIds":param.inputFrom.handleIds||param.inputFrom.bransId,
				"handleType":param.inputFrom.handleIds==""?'organization':'user',
		},
		transformRequest: [function (data) {/*转成fromdata*/
              let ret = ''
              for (let it in data) {
                ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
              }
              return ret
         }],
  }).then((res) => {
  	 console.log(res);
  	 if(res.data.result.code=='200'||res.data.result.code==200){
  	 	ev.$message.success('操作成功');
  	 	ev.closeDialog();
  	 }else{
  	 	ev.$message.error(res.data.result.msg);
	 	ev.closeDialog();
  	 }
  })
.catch((error) => {
	ev.$message.error('网络出错，请稍后再试');
   console.log('出错',error);
 });
}

export const apiUpload=(kid,sid)=>{/*转上传文件的地址*/
	return developUrl+developDK+'file/uploads?access_token='+TOKEN;
}

export const apiGuanLian=(uploadId,formId,nodeId)=>{/*关联*/
	return axios({
		method:'post',
		url:developUrl+developDK+'file/update?access_token='+TOKEN+'&uploadId='+uploadId+'&formId='+formId+'&nodeId='+nodeId,
	}).then((res)=>{
		console.log(res);
	})
}

export const apiShowFuJian=(ev,formId,nodeId)=>{/*详情里面的附件*/
	return axios({
		method:'post',
		url:developUrl+developDK+'file/showList?access_token='+TOKEN+'&keyId='+formId+'&nodeId='+nodeId,
	}).then((res)=>{
		for (let i = 0; i < res.data.length; i++) {/*URL转换*/
			res.data[i].id = developUrl+developDK+'file/downLoad?id='+res.data[i].id;
			
		}
		if(nodeId!='-1'){
			ev.fujianNodeURL=res.data;/*暂时先这样处理，等待*/
		}else{
			ev.fujianURL=res.data;/*暂时先这样处理，等待*/
		}
	})
}

export const apiApplyDan=(ev,param)=>{/*申请工单*/
	return axios ({
		method:'post',
		url: developUrl+developDK+'synergetic/apply?access_token='+TOKEN,
		headers : {
	      'Content-Type': 'application/x-www-form-urlencoded'
		},
		data:{
			applyTitle:param.applyTitle,
			workProcess:param.workProcess,
			description:param.description,
			assistanceRequirements:param.assistanceRequirements
		},
		transformRequest: [function (data) {/*转成fromdata*/
              let ret = ''
              for (let it in data) {
                ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
              }
              return ret
         }],
	}).then(res=>res).catch((err)=>{
		ev.$message.error(err);
  		console.log('出错',err);
	})
}

export const apiAdress=(ev,handleIds)=>{/*选择处理人员*/
	console.log(handleIds);
	let handleIdArray = handleIds.split(',');
	console.log(handleIdArray);
	for (let i = 0; i < handleIdArray.length; i++) {
					axios ({
						method:'post',
						url: developUrl+tongxunDK+'uaa/organization/selectByMyDept/'+handleIdArray[i]+'?access_token='+TOKEN,
					}).then((res)=>{
						console.log(res);
						if(res.data.code=="S100101"){
							for (let i in res.data.data.data.userList){
								ev.details.people.push(res.data.data.data.userList[i]);
								
							}
							for (let i in res.data.data.data.organizationList){
								ev.details.brans.push(res.data.data.data.organizationList[i])
							}
						
							
						}
						console.log(ev.details);
					}).catch((err)=>{
				  		console.log('出错',err);
					})
	}

}

export const apiBrans=(ev)=>{/*选择处理部门*/
	return axios ({
		method:'post',
		url:developUrl+tongxunDK+'uaa/organization/selectByMyOrg?access_token='+TOKEN,
	}).then((res)=>{
		console.log(res);
		if(res.data.code=="S100101"){
			ev.details.brans.push(res.data.data.data);
			console.log(ev.details.brans);
			
		}
	}).catch((err)=>{
  		console.log('出错',err);
	})
}

export const apiChangeBrans=(ev,val)=>{/*选择部门换数据*/
//	console.log(val);
	return	axios({
	    method: 'post',
	    url:developUrl+tongxunDK+'uaa/organization/selectByMyDept/'+val+'?access_token='+TOKEN,
	})
	.then((res)=>{
		if(res.data.code=="S100101"){
			console.log(res);
			ev.details.people=res.data.data.data.userList;
			ev.details.brans=res.data.data.data.organizationList;
			dealTopBranchs(res.data.data.data.myParent.data,ev);
		}
	})
	.catch(function (error) {
	  console.log('网络出错',error);
	})
}


export const apiCheckLiucheng=(ev)=>{/*工单申请打开流程图*/
	return	axios({
	    method: 'get',
	    url:developUrl+developDK+'act/showAll?access_token='+TOKEN,/*陈林峰*/
	}).then((res)=>{
		console.log(res);
		ev.liuchengLi = res.data;
	})
}


export const apiChooseLiucheng=(ev,id)=>{/*有id，申请接口更换流程图*/
	ev.loadingOpen('.right_liu');
	return	axios({
	    method: 'get',
	    url:developUrl+developDK+'act/getShineProcImage1?access_token='+TOKEN+'&deploymentId='+id,/*陈林峰*/
	}).then((res)=>{
		console.log(res);
		
		ev.liuchengImg = "data:image/png;base64,"+encodeURI(res.data.images[0]);
		ev.loadingClose();
	})
}

export const apiShowNode=(ev,id)=>{/*工单详情里面显示的环节信息*/
	return	axios({
	    method: 'get',
	    url:developUrl+developDK+'synergetic/get-node/'+id+'?access_token='+TOKEN,/*陈林峰*/
	}).then((res)=>{
		console.log(res);
		if(res.data.codeData){
			for (let i = 0; i < res.data.codeData.length; i++) {
				res.data.codeData[i].handleRecord.createdDate =dealTime(res.data.codeData[i].handleRecord.createdDate)
				res.data.codeData[i].handleRecord.updatedDate =dealTime(res.data.codeData[i].handleRecord.updatedDate)
			}
		}

		ev.historyUl = res.data.codeData;
	})
}

export const apiShowPingJia=(ev,id)=>{/*工单详情里面显示的评价内容*/
	return	axios({
	    method: 'get',
	    url:developUrl+developDK+'userComment/searchComment/'+id+'?access_token='+TOKEN,
	}).then((res)=>{
		console.log(res);
		ev.pingjia = res.data;
	})
}

export const apiShowLiuCheng=(ev,id)=>{/*工单详情里面显示的流程图片*/
	return	axios({
	    method: 'get',
	    url:developUrl+developDK+'act/getShineProcImage?access_token='+TOKEN+'&processInstanceId='+id,/*陈林峰*/
	}).then((res)=>{
		console.log(res);
//		console.log("data:image/png;base64,"+encodeURI(res.data.images[0]));
		ev.liuChengImg = "data:image/png;base64,"+encodeURI(res.data.images[0]);
	
	})
}

export const apiGetRole=(ev,val)=>{/*评价获取角色*/
	return	axios({
	    method: 'post',
	    url:developUrl+developDK+'userComment/searchUserRole/'+val.processInstanceId+'?access_token='+TOKEN,/*陈林峰*/
	}).then((res)=>{
		console.log(res);
		ev.pingjiaType = res.data;
	})
}

export const apiPostPingJia=(ev,form1,form2,formId,pingjiaType)=>{/*提交评价*/
	let data = {};
	if(pingjiaType==='shenqing'){
		data = [
	    		{
	    			"formId":formId,
	    			"msg" : form1.desc,
	    			"level" :form1.start,
	    			"userRole":pingjiaType,
	    			"handlerUserRole" :"fenfa"
	    		},
	    		{
	    			"formId":formId,
	    			"msg" : form2.desc,
	    			"level" :form2.start,
	    			"userRole":pingjiaType,
	    			"handlerUserRole" :"fankui"
	    		}
	    	];
	}else if(pingjiaType==='fankui'){
		data = [{
					"formId":formId,
	    			"msg" : form1.desc,
	    			"level" :form1.start,
	    			"userRole":pingjiaType,
	    			"handlerUserRole" :"fenfa"
				}]
	}else if(pingjiaType==='fenfa'){
		data = [{
					"formId":formId,
	    			"msg" : form1.desc,
	    			"level" :form1.start,
	    			"userRole":pingjiaType,
	    			"handlerUserRole" :"fankui"
				}]
	}
	
	return	axios({
	    method: 'post',
	    url:developUrl+developDK+'userComment/addUserComment?access_token='+TOKEN,
	    data:data
	}).then((res)=>{
		console.log(res);
		if(res.data>0){
			ev.$message.success('评价成功');
			location.reload();
		}else{
			ev.$message.error('评价不成功');
//			location.reload();
		}
	})
}

export const apiSearchBrans=(ev,val)=>{/*搜索部门*/
	return	axios({
	    method: 'post',
	    url:developUrl+tongxunDK+'uaa/organization/searchByName?access_token='+TOKEN,
	    data:{
	    	"name":val
	    }
	}).then((res)=>{
		console.log(res);
		ev.details.brans= res.data.data.data.organizationList;
	})
}



function dealTime(val){/*修正时间格式*/
	  	let date = new Date(val);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
        let Y = date.getFullYear() + '-';
        let M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
        let D = date.getDate() + ' ';
        let h = date.getHours() + ':';
        let m = date.getMinutes() + ':';
        let s = date.getSeconds();
        return Y+M+D+h+m+s;
}

function dealTopBranchs(parent,ev){/*递归，排成数组，右上角显示*/
	arr.push(parent);
	if(parent.organizationVos!=undefined){
		dealTopBranchs(parent.organizationVos[0],ev);
	}else{
		ev.totelTitle =arr;
		arr = [];
		return ;
	}
}


